import { RouteRecordRaw } from 'vue-router'
import { useLoginStore } from '@/store/login/login'
import { sessionCache } from '@/utils/storage'
import router from '@/router'

const modules = import.meta.glob('../views/**/*.vue')

export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
	const routes: RouteRecordRaw[] = []

	function _recurseGetRoute(menus: any[]) {
		for (const menu of menus) {
			if (!menu.children) {
				const route = {
					name: menu.name,
					path: menu.path,
					meta: {
						title: menu.meta.title
					},
					component: modules['../views' + menu.component]
				}
				routes.push(route)
			} else {
				_recurseGetRoute(menu.children)
			}
		}
	}
	_recurseGetRoute(userMenus)

	return routes
}

// 面包屑
interface IBreadcrumb {
	title: string
	path?: string
}

function pathMapToMenu(userMenus: any[], currentPath: string, breadcrumbs?: IBreadcrumb[]): any {
	for (const menu of userMenus) {
		if (menu.type === 1) {
			const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
			if (findMenu) {
				breadcrumbs?.push({ title: menu.title })
				breadcrumbs?.push({ title: findMenu.title })
				return findMenu
			}
		} else if (menu.type === 2 && menu.path === currentPath) {
			return menu
		}
	}
}

export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
	const breadcrumbs: IBreadcrumb[] = []
	pathMapToMenu(userMenus, currentPath, breadcrumbs)
	return breadcrumbs
}

// 跳转时tag标签的处理
export function handleTagList() {
	const loginStore = useLoginStore()
	router.afterEach((to) => {
		const hasTag = loginStore.headerTags.findIndex((item) => item.path == to.path)
		if (hasTag == -1) {
			const tag = {
				label: to.meta.title,
				path: to.path
			}
			loginStore.headerTags.push(tag)
			sessionCache.setItem('headerTags', loginStore.headerTags)
		}
	})
}

// 将菜单列表转为树结构
